﻿using System;
using System.Data;
using System.Data.SqlTypes;
using System.IO;
using System.Text;
using System.Web;
using System.Xml;

namespace CommonHelper.Common
{
    /// <summary>
    /// Description:Use it for data conversion
    /// Created by:lhan
    /// Created:2013/3/29
    /// Last modified by: lhan
    /// Last modified:2013/3/29
    /// Version:1.0.0.0
    /// </summary>
    public class ConvertHelper
    {
        #region 类型转换
        public static Boolean ConvertBoolean(string value)
        {
            if (value == null || string.IsNullOrEmpty(value.Trim()) || Equals(value.Trim().ToLower(), "system.object"))
                return false;
            if (Equals(value.Trim(), "1"))
                return true;
            if (Equals(value.Trim().ToLower(), "true"))
                return true;
            return false;
        }
        public static Boolean ConvertBoolean(int value)
        {
            if (value == 1)
                return true;
            return false;
        }
        
        public static Boolean ConvertBoolean(object value)
        {
            if (value == null || string.IsNullOrEmpty(value.ToString().Trim()))
                return false;
            if (Equals(value.ToString().Trim(), "1"))
                return true;
            if (Equals(value.ToString().Trim().ToLower(), "true"))
                return true;
            return false;
        }

        public static string ConvertString(object obj)
        {
            if (obj == null || Equals(obj.ToString().ToLower().Trim(), "system.object"))
                return string.Empty;
            return obj.ToString().Trim();
        }

        /// <summary>
        /// 转换为整型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static int ConvertInt(object obj)
        {
            if (obj == null)
                return 0;
            if (Equals(obj, DBNull.Value))
                return 0;
            if (Equals(obj.ToString().ToLower().Trim(), "system.object"))
                return 0;
            if (Equals(obj.ToString().Trim(), string.Empty))
                return 0;
            int i;
            if (Int32.TryParse(obj.ToString(), out i))
            {
                return i;
            }
            return 0;
        }
        public static int ConvertInt(string obj)
        {
            if (string.IsNullOrEmpty(obj) || Equals(obj.Trim(), string.Empty))
                return 0;
            if (string.IsNullOrEmpty(obj.Trim()))
                return 0;
            if (Equals(obj.ToLower().Trim(), "system.object"))
                return 0;
            int i;
            if (Int32.TryParse(obj.Trim(), out i))
            {
                return i;
            }
            return 0;
        }
        public static int ConvertInt(float obj)
        {
            return Convert.ToInt32(obj);
        }

        public static int ConvertInt(double obj)
        {
            return Convert.ToInt32(obj);
        }

        public static int ConvertInt(UInt32 obj)
        {
            return Convert.ToInt32(obj);
        }
        public static int ConvertInt(long obj)
        {
            return Convert.ToInt32(obj);
        }

        /// <summary>
        /// 转换为长整型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static long ConvertLong(object obj)
        {
            if (obj == null)
                return 0;
            if (Equals(obj.ToString(), string.Empty))
                return 0;
            if (Equals(obj, DBNull.Value))
                return 0;
            if (Equals(obj.ToString().ToLower().Trim(), "system.object"))
                return 0;
            long i;
            if (Int64.TryParse(obj.ToString(), out i))
            {
                return i;
            }
            return 0;
        }
        public static long ConvertLong(string obj)
        {
            if (obj == null)
                return 0;
            if (Equals(obj.Trim(), string.Empty))
                return 0;
            if (Equals(obj.ToLower().Trim(), "system.object"))
                return 0;
            long i;
            if (Int64.TryParse(obj, out i))
            {
                return i;
            }
            return 0;
        }
        public static long ConvertLong(int obj)
        {
            return Convert.ToInt64(obj);
        }

        public static long ConvertLong(float obj)
        {
            return Convert.ToInt64(obj);
        }
        public static long ConvertLong(double obj)
        {
            return Convert.ToInt64(obj);
        }
        public static long ConvertLong(UInt32 obj)
        {
            return Convert.ToInt64(obj);
        }
        /// <summary>
        /// 转换为长整型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static float ConvertFloat(object obj)
        {
            if (obj == null)
                return 0;
            if (Equals(obj.ToString(), string.Empty))
                return 0;
            if (Equals(obj, DBNull.Value))
                return 0;
            if (Equals(obj.ToString().ToLower().Trim(), "system.object"))
                return 0;
            float i;
            if (float.TryParse(obj.ToString(), out i))
            {
                return i;
            }
            return 0;
        }
        public static float ConvertFloat(string obj)
        {
            if (obj == null)
                return 0;
            if (Equals(obj.Trim(), string.Empty))
                return 0;
            if (Equals(obj.ToLower().Trim(), "system.object"))
                return 0;
            float i;
            if (float.TryParse(obj, out i))
            {
                return i;
            }
            return 0;
        }
        public static float ConvertFloat(int obj)
        {
            return Convert.ToInt64(obj);
        }

        public static float ConvertFloat(double obj)
        {
            return Convert.ToInt64(obj);
        }
        public static float ConvertFloat(UInt32 obj)
        {
            return Convert.ToInt64(obj);
        }
        public static long ConvertFloat(long obj)
        {
            return Convert.ToInt64(obj);
        }
        /// <summary>
        /// 转换为高精度型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static decimal ConvertDecimal(object obj)
        {
            if (obj == null)
                return 0;
            if (obj == DBNull.Value)
                return 0;
            if (obj.ToString().ToLower().Trim() == "system.object")
                return 0;
            if (string.IsNullOrEmpty(obj.ToString().Trim()))
                return 0;
            decimal i;
            if (decimal.TryParse(obj.ToString(), out i))
            {
                return i;
            }
            return 0;
        }

        /// <summary>
        /// 判断是否是正数字字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static double ConvertDouble(object obj)
        {
            if (obj == null)
                return 0;
            if (obj == DBNull.Value)
                return 0;
            if (obj.ToString().ToLower().Trim() == "system.object")
                return 0;
            if (string.IsNullOrEmpty(obj.ToString().Trim()))
                return 0;
            double i;
            if (double.TryParse(obj.ToString(), out i))
            {
                return i;
            }
            return 0;
        }

        /// <summary>
        /// 判断是否是正数字字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static double ConvertDouble(string obj)
        {
            if (obj == null)
                return 0;
            if (string.IsNullOrEmpty(obj))
                return 0;
            if (obj.ToLower().Trim() == "system.object")
                return 0;
            if (string.IsNullOrEmpty(obj.Trim()))
                return 0;
            double i;
            if (double.TryParse(obj, out i))
            {
                return i;
            }
            return 0;
        }

        /// <summary>
        /// 转换为高精度型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static decimal ConvertDecimal(string obj)
        {
            if (obj == null)
                return 0;
            if (string.IsNullOrEmpty(obj.Trim()))
                return 0;
            if (obj.ToLower().Trim() == "system.object")
                return 0;
            decimal i;
            if (decimal.TryParse(obj, out i))
            {
                return i;
            }
            return 0;
        }
        /// <summary>
        /// 转换为日期型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns>转换失败是返回1753/01/01 00:00:00（数据库最小时间）</returns>
        public static DateTime ConvertDateTime(object obj)
        {
            if (obj == null)
                return SqlDateTime.MinValue.Value;
            if (obj == DBNull.Value)
                return SqlDateTime.MinValue.Value;
            if (obj.ToString().ToLower().Trim() == "system.object")
                return SqlDateTime.MinValue.Value;
            if (string.IsNullOrEmpty(obj.ToString().Trim()))
                return SqlDateTime.MinValue.Value;
            DateTime i;
            if (DateTime.TryParse(obj.ToString(), out i))
            {
                return i;
            }
            return SqlDateTime.MinValue.Value;
        }

        public static decimal ConvertDecimal(int obj)
        {
            return Convert.ToDecimal(obj);
        }
        public static decimal ConvertDecimal(float obj)
        {
            return Convert.ToDecimal(obj);
        }
        public static decimal ConvertDecimal(double obj)
        {
            return Convert.ToDecimal(obj);
        }
        public static decimal ConvertDecimal(UInt32 obj)
        {
            return Convert.ToDecimal(obj);
        }
        public static decimal ConvertDecimal(long obj)
        {
            return Convert.ToDecimal(obj);
        }

        public static double ConvertDouble(int obj)
        {
            return Convert.ToDouble(obj);
        }
        public static double ConvertDouble(float obj)
        {
            return Convert.ToDouble(obj);
        }
        public static double ConvertDouble(UInt32 obj)
        {
            return Convert.ToDouble(obj);
        }
        public static double ConvertDouble(long obj)
        {
            return Convert.ToDouble(obj);
        }
        /// <summary>
        /// 转换为日期型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static DateTime ConvertDateTime(string obj)
        {
            if (obj == null)
                return SqlDateTime.MinValue.Value;
            if (string.IsNullOrEmpty(obj.Trim()))
                return SqlDateTime.MinValue.Value;
            if (obj.ToLower().Trim() == "system.object")
                return SqlDateTime.MinValue.Value;
            DateTime i;
            if (DateTime.TryParse(obj, out i))
            {
                return i;
            }
            return SqlDateTime.MinValue.Value;
        }
        #endregion

        #region  数据转换成xml
        /**/
        /// <summary>
        /// 将DataTable对象转换成XML字符串
        /// </summary>
        /// <param name="dt">DataTable对象</param>
        /// <returns>XML字符串</returns>
        public static string CDataToXml(DataTable dt)
        {
            if (dt != null)
            {
                try
                {
                    byte[] temp;
                    using (var ms = new MemoryStream())
                    {
                        using (var xmlWt = new XmlTextWriter(ms, Encoding.Unicode))
                        {
                            dt.WriteXml(xmlWt);
                        }
                        var count = (int)ms.Length;
                        temp = new byte[count];
                        ms.Seek(0, SeekOrigin.Begin);
                        ms.Read(temp, 0, count);
                    }
                    //返回Unicode编码的文本
                    var ucode = new UnicodeEncoding();
                    string returnValue = ucode.GetString(temp).Trim();
                    return returnValue;
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
            }
            return string.Empty;
        }

        /**/
        /// <summary>
        /// 将DataSet对象中指定的Table转换成XML字符串
        /// </summary>
        /// <param name="ds">DataSet对象</param>
        /// <param name="tableIndex">DataSet对象中的Table索引</param>
        /// <returns>XML字符串</returns>
        public static string CDataToXml(DataSet ds, int tableIndex)
        {
            if (ds != null && ds.Tables.Count>0)
            {
                if (tableIndex != -1 && ds.Tables.Count >= tableIndex)
                {
                    return CDataToXml(ds.Tables[tableIndex]);
                }
                if (ds.Tables.Count > 0)
                {
                    return CDataToXml(ds.Tables[0]);
                }
            }
            return string.Empty;
        }

        /**/
        /// <summary>
        /// 将DataSet对象转换成XML字符串
        /// </summary>
        /// <param name="ds">DataSet对象</param>
        /// <returns>XML字符串</returns>
        public static string CDataToXml(DataSet ds)
        {
            return CDataToXml(ds, -1);
        }
        /**/
        /// <summary>
        /// 将DataView对象转换成XML字符串
        /// </summary>
        /// <param name="dv">DataView对象</param>
        /// <returns>XML字符串</returns>
        public static string CDataToXml(DataView dv)
        {
            return CDataToXml(dv.Table);
        }
        /**/
        /// <summary>
        /// 将DataSet对象数据保存为XML文件
        /// </summary>
        /// <param name="dt">DataSet</param>
        /// <param name="xmlFilePath">XML文件路径(相对路径)</param>
        /// <returns>bool值</returns>
        public static bool CDataToXmlFile(DataTable dt, string xmlFilePath)
        {
            if ((dt != null) && (!string.IsNullOrEmpty(xmlFilePath)))
            {
                string path = HttpContext.Current.Server.MapPath(xmlFilePath);
                try
                {
                    byte[] temp;
                    using (var ms = new MemoryStream())
                    {
                        using (var xmlWt = new XmlTextWriter(ms, Encoding.Unicode))
                        {
                            dt.WriteXml(xmlWt);
                        }
                        var count = (int)ms.Length;
                        temp = new byte[count];
                        ms.Seek(0, SeekOrigin.Begin);
                        ms.Read(temp, 0, count);
                    }
                    //返回Unicode编码的文本
                    var ucode = new UnicodeEncoding();
                    //写文件
                    using (var sw = new StreamWriter(path))
                    {
                        sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                        sw.WriteLine(ucode.GetString(temp).Trim());
                        sw.Close();
                    }
                    return true;
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }

            }
            return false;
        }

        /**/
        /// <summary>
        /// 将DataSet对象中指定的Table转换成XML文件
        /// </summary>
        /// <param name="ds">DataSet对象</param>
        /// <param name="tableIndex">DataSet对象中的Table索引</param>
        /// <param name="xmlFilePath">xml文件路径</param>
        /// <returns>bool]值</returns>
        public static bool CDataToXmlFile(DataSet ds, int tableIndex, string xmlFilePath)
        {
            if (tableIndex != -1)
            {
                return CDataToXmlFile(ds.Tables[tableIndex], xmlFilePath);
            }
            return CDataToXmlFile(ds.Tables[0], xmlFilePath);
        }

        /**/
        /// <summary>
        /// 将DataSet对象转换成XML文件
        /// </summary>
        /// <param name="ds">DataSet对象</param>
        /// <param name="xmlFilePath">xml文件路径</param>
        /// <returns>bool]值</returns>
        public static bool CDataToXmlFile(DataSet ds, string xmlFilePath)
        {
            return CDataToXmlFile(ds, -1, xmlFilePath);
        }
        /**/
        /// <summary>
        /// 将DataView对象转换成XML文件
        /// </summary>
        /// <param name="dv">DataView对象</param>
        /// <param name="xmlFilePath">xml文件路径</param>
        /// <returns>bool]值</returns>
        public static bool CDataToXmlFile(DataView dv, string xmlFilePath)
        {
            return CDataToXmlFile(dv.Table, xmlFilePath);
        }


        #endregion

        #region  XML形式的字符串、XML文江转换成DataSet、DataTable格式
        /**/
        /// <summary>
        /// 将Xml内容字符串转换成DataSet对象
        /// </summary>
        /// <param name="xmlStr">Xml内容字符串</param>
        /// <returns>DataSet对象</returns>
        public static DataSet CXmlToDataSet(string xmlStr)
        {
            if (!string.IsNullOrEmpty(xmlStr))
            {
                try
                {
                    var ds = new DataSet();
                    //读取字符串中的信息
                    using (var strStream = new StringReader(xmlStr))
                    {
                        using (var xmlrdr = new XmlTextReader(strStream))
                        {
                            ds.ReadXml(xmlrdr);
                        }
                    }
                    return ds;
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }

            }
            return null;
        }

        /**/
        /// <summary>
        /// 将Xml字符串转换成DataTable对象
        /// </summary>
        /// <param name="xmlStr">Xml字符串</param>
        /// <param name="tableIndex">Table表索引</param>
        /// <returns>DataTable对象</returns>
        public static DataTable CXmlToDatatTable(string xmlStr, int tableIndex)
        {
            return CXmlToDataSet(xmlStr).Tables[tableIndex];
        }
        /**/
        /// <summary>
        /// 将Xml字符串转换成DataTable对象
        /// </summary>
        /// <param name="xmlStr">Xml字符串</param>
        /// <returns>DataTable对象</returns>
        public static DataTable CXmlToDatatTable(string xmlStr)
        {
            return CXmlToDataSet(xmlStr).Tables[0];
        }
        /**/
        /// <summary>
        /// 读取Xml文件信息,并转换成DataSet对象
        /// </summary>
        /// <remarks>
        /// DataSet ds = new DataSet();
        /// ds = CXmlFileToDataSet("/XML/upload.xml");
        /// </remarks>
        /// <param name="xmlFilePath">Xml文件地址</param>
        /// <returns>DataSet对象</returns>
        public static DataSet CXmlFileToDataSet(string xmlFilePath)
        {
            if (!string.IsNullOrEmpty(xmlFilePath))
            {
                string path = HttpContext.Current.Server.MapPath(xmlFilePath);
                try
                {
                    var xmldoc = new XmlDocument();
                    //根据地址加载Xml文件
                    xmldoc.Load(path);

                    var ds = new DataSet();
                    //读取文件中的字符流
                    using (var strStream = new StringReader(xmldoc.InnerXml))
                    {
                        using (var xmlrdr = new XmlTextReader(strStream))
                        {
                            ds.ReadXml(xmlrdr);
                        }
                    }
                    return ds;
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
            }
            return null;
        }

        /**/
        /// <summary>
        /// 读取Xml文件信息,并转换成DataTable对象
        /// </summary>
        /// <param name="xmlFilePath">xml文江路径</param>
        /// <param name="tableIndex">Table索引</param>
        /// <returns>DataTable对象</returns>
        public static DataTable CXmlToDataTable(string xmlFilePath, int tableIndex)
        {
            return CXmlFileToDataSet(xmlFilePath).Tables[tableIndex];
        }
        /**/
        /// <summary>
        /// 读取Xml文件信息,并转换成DataTable对象
        /// </summary>
        /// <param name="xmlFilePath">xml文江路径</param>
        /// <returns>DataTable对象</returns>
        public static DataTable CXmlToDataTable(string xmlFilePath)
        {
            return CXmlFileToDataSet(xmlFilePath).Tables[0];
        }



        #endregion

    }
}